<?php
/**
  * wechat php test
*/
define("TOKEN", "weixinstz");
function debug($msg){
	$call_stack = debug_backtrace() ;
    
    # index 0 means the latest caller's information
    $filename = basename($call_stack[ 0 ][ "file" ]);
	$lineno   = $call_stack[ 0 ][ "line" ] ;
	error_log(sprintf("%s\t%s %s:%s\n",date('Y-m-d\TH:i:sO'),$msg,$filename,$lineno),3,'stz.log');
}

$wechatObj = new wechatCallbackapi();
debug("create menu result:".$wechatObj->create_menu());

debug("start ...");
if (isset($_GET['echostr'])) {
		debug("echostr".$_GET['echostr']);
	    $wechatObj->valid();
}else{
		debug("response");
	    $wechatObj->responseMsg();
}


class wechatCallbackapi
{	
	private $appID ='wxa62092534b473ea5';
	private $appsecret = '946812688f28f3e3539bc4adcb6b901f';
	

	private function json_to_array($json_str)
	{
		return json_decode($json_str,true);
	}

	private function http_post($url,$body)
	{
		// $query = http_build_query($this->json_to_array($json_params));
		
		// Create Http context details
		$contextData = array ( 
					'method' => 'POST',
					'header'  => 'Content-type: application/x-www-form-urlencoded',
					'content'=> $body );
		
		// Create context resource for our request
		$context = stream_context_create (array ( 'http' => $contextData ));
		
		// Read page rendered as result of your POST request
		$result =  file_get_contents (
					  $url,  // page url
					  false,
					  $context);
		
		// Server response is now stored in $result variable so you can process it
		return $result;
	}

	public function create_menu()
	{	
		$access_token = $this->get_access_token();
		debug("create menu:".print_r($access_token,true));
		$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token['access_token'];
		$menu = <<< EOF
		{
			"button":[
			{	
				 "type":"click",
				 "name":"今日歌曲",
				 "key":"V1001_TODAY_MUSIC"
			 },
			 {
				  "name":"菜单",
				  "sub_button":[
				  {	
					  "type":"view",
					  "name":"搜索",
					  "url":"http://www.soso.com/"
				   },
				   {
					  "type":"click",
					  "name":"赞一下我们",
					  "key":"V1001_GOOD"
				   }]
			  }]
		}
EOF;
		return $this->http_post($url,$menu);
	}
	public function get_access_token()
	{  // http get
		return $this->json_to_array(file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appID&secret=$this->appsecret"));
	}
	
	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

	public function getUserInfo($openID){

		$access_token = $this->get_access_token();
		debug("create menu:".print_r($access_token,true));
		return file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token['access_token']."&openid=$openID&lang=zh_CN");

	}

	public function echo_text_msg($fromUsername, $toUsername,$default_content='Welcome to our wechat world!'){
		$textTpl = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[text]]></MsgType>
		<Content><![CDATA[%s]]></Content>
		<FuncFlag>0</FuncFlag>
		</xml>"; 
		$resultStr = sprintf($textTpl, $fromUsername, $toUsername, time(),$default_content);
		debug("ok: $resultStr\n",3,'stz.log');
		echo $resultStr;
	}
    public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

		debug("postStr=>$postStr");
      	//extract post data
		if (!empty($postStr)){
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
				$msg_type = trim($postObj->MsgType);
				// debug("From User info:".$wechatObj->getUserInfo($fromUsername));
                            
				debug("msgType: $msg_type");
				switch($msg_type){	
					case 'text':
						$keyword = trim($postObj->Content);
						if(!empty( $keyword ))
						{
							$this->echo_text_msg($fromUsername,$toUsername);
						}else{
							debug("wrong");
							echo "Input something...";
						}
						break;
					case 'event':
						$eventKey = trim($postObj->EventKey);
						if ($eventKey == 'V1001_TODAY_MUSIC'){
							$this->echo_text_msg($fromUsername,$toUsername,"今日歌曲:月亮代表我的心");
						}else{
							$this->echo_text_msg($fromUsername,$toUsername,"Unknow eventkey: $eventKey");
						}
						break;
					default:
						$this->echo_text_msg($fromUsername,$toUsername,"Unknow msg type: $msg_type");
						break;

			}

        }else {
        	echo "";
		    debug("exit ...");
        	exit;
        }
    }
		
	private function checkSignature()
	{
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}
?>
